package _hash;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/*

https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html
https://leetcode.cn/problems/two-sum/description/

1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出 和为目标值 target  的那 两个 整数，并返回它们的数组下标。

输入：nums = [2,7,11,15], target = 9
输出：[0,1]

输入：nums = [3,2,4], target = 6
输出：[1,2]
*/
public class leetcode_1_Java {
    @Test
    public void test_1() {
        int[] actual = twoSum(new int[]{2, 7, 11, 15}, 9);
        int[] expect = new int[]{0, 1};
        Assert.assertEquals(Arrays.toString(expect), Arrays.toString(actual));
    }

    @Test
    public void test_2() {
        int[] actual = twoSum(new int[]{3,2,4}, 6);
        int[] expect = new int[]{1, 2};
        Assert.assertEquals(Arrays.toString(expect), Arrays.toString(actual));
    }


    private int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length - 1);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
